<template>
    <view>
        <Headernav-music></Headernav-music>
        <!-- 搜索框 -->
        <view class="search-box">
            <input
                class="search-input"
                v-model="searchWord"
                placeholder="搜索歌曲/歌手"
                @input="onInputChange"
                @confirm="onSearch"
            />
            <text class="iconfont icon-sousuo" @click="onSearch"></text>
        </view>
        
        <!-- 历史记录 -->
        <view v-if="!searchWord && historyList.length > 0" class="history-container">
            <view class="history-header">
                <text class="history-title">搜索历史</text>
                <text class="clear-history" @click="clearHistory">清空历史</text>
            </view>
            <view class="history-list">
                <view
                    class="history-item"
                    v-for="(item, index) in historyList"
                    :key="index"
                    :class="{ 'deleting': deletingIndex === index }"
                >
                    <text class="iconfont icon-clock"></text>
                    <text class="history-word" @click="handleHistoryClick(item)">{{ item }}</text>
                    <text 
                        class="iconfont icon-delete" 
                        @click.stop="deleteHistory(index)"
                    ></text>
                </view>
            </view>
        </view>
        
        <!-- 热门搜索 -->
        <view v-if="!searchWord && hotSearchList.length > 0" class="hot-search">
            <view class="hot-search-title">热门搜索</view>
            <view class="hot-search-list">
                <view
                    class="hot-search-item"
                    v-for="(item, index) in hotSearchList"
                    :key="index"
                    @click="handleHotSearchClick(item.searchWord)"
                >
                    <text class="hot-search-rank" :class="{'top-three': index < 3}">{{ index + 1 }}</text>
                    <text class="hot-search-word">{{ item.searchWord }}</text>
                </view>
            </view>
        </view>
        
        <!-- 搜索建议 -->
        <view v-if="searchWord && suggestList.length > 0 && !showSearchResult" class="search-suggest">
            <view class="search-suggest-list">
                <view
                    class="search-suggest-item"
                    v-for="(item, index) in suggestList"
                    :key="index"
                    @click="handleSuggestClick(item)"
                >
                    <text class="iconfont icon-sousuo"></text>
                    <text>{{ item }}</text>
                </view>
            </view>
        </view>
        
        <!-- 搜索结果 -->
        <view v-if="showSearchResult" class="search-result">
            <view class="result-header">
                <text class="result-title">搜索结果</text>
                <text class="result-count">{{ searchResult.length }} 首歌曲</text>
            </view>
            <view class="search-result-list">
                <view
                    class="search-result-item"
                    v-for="(item, index) in searchResult"
                    :key="index"
                    @click="handleSongClick(item.id)"
                >
                    <view class="song-info">
                        <text class="song-index">{{ index + 1 }}</text>
                        <view class="song-details">
                            <view class="song-name">{{ item.name }}</view>
                            <view class="song-artist">{{ item.artists.map(artist => artist.name).join(', ') }}</view>
                        </view>
                    </view>
                    <text class="iconfont icon-play"></text>
                </view>
            </view>
        </view>
        
        <!-- 无结果提示 -->
        <view v-if="searchWord && !showSearchResult && !suggestList.length" class="empty-result">
            <text class="iconfont icon-search-empty"></text>
            <text class="empty-text">没有找到相关结果</text>
        </view>
    </view>
</template>

<script>
import { searchHot, searchWord, searchSuggest } from '../../common/api.js';

export default {
    data() {
        return {
            searchWord: '',
            hotSearchList: [],
            suggestList: [],
            searchResult: [],
            historyList: [],
            deletingIndex: -1,
            showSearchResult: false
        };
    },
    onLoad() {
        this.getHotSearch();
        this.loadHistory();
    },
    methods: {
        async getHotSearch() {
            try {
                const res = await searchHot();
                if (res.data.code === 200) {
                    this.hotSearchList = res.data.data;
                }
            } catch (err) {
                console.error('获取热门搜索失败:', err);
            }
        },
        async onInputChange() {
            if (this.searchWord.trim()) {
                try {
                    const res = await searchSuggest(this.searchWord);
                    if (res.data.code === 200 && res.data.result.allMatch) {
                        this.suggestList = res.data.result.allMatch.map(item => item.keyword);
                    } else {
                        this.suggestList = [];
                    }
                } catch (err) {
                    console.error('获取搜索建议失败:', err);
                    this.suggestList = [];
                }
                this.showSearchResult = false;
            } else {
                this.suggestList = [];
                this.showSearchResult = false;
            }
        },
        async onSearch() {
            const keyword = this.searchWord.trim();
            if (keyword) {
                try {
                    const res = await searchWord(keyword);
                    if (res.data.code === 200 && res.data.result.songs) {
                        this.searchResult = res.data.result.songs;
                        this.addHistory(keyword);
                        this.showSearchResult = true;
                        this.suggestList = [];
                    } else {
                        this.searchResult = [];
                        this.showSearchResult = false;
                    }
                } catch (err) {
                    console.error('搜索失败:', err);
                    this.searchResult = [];
                    this.showSearchResult = false;
                }
            }
        },
        // 历史记录相关方法
        loadHistory() {
            try {
                const history = uni.getStorageSync('searchHistory');
                if (history) {
                    this.historyList = JSON.parse(history);
                }
            } catch (err) {
                console.error('加载历史记录失败:', err);
                this.historyList = [];
            }
        },
        addHistory(word) {
            const keyword = word.trim();
            if (!keyword) return;
            
            // 检查是否已存在，存在则移除
            const index = this.historyList.indexOf(keyword);
            if (index !== -1) {
                this.historyList.splice(index, 1);
            }
            
            // 添加到最前面
            this.historyList.unshift(keyword);
            
            // 限制数量
            if (this.historyList.length > 10) {
                this.historyList.pop();
            }
            
            // 保存到本地存储
            uni.setStorageSync('searchHistory', JSON.stringify(this.historyList));
        },
        deleteHistory(index) {
            uni.showModal({
                title: '确认删除',
                content: `确定要删除"${this.historyList[index]}"的搜索历史吗？`,
                confirmColor: '#d43c33',
                success: (res) => {
                    if (res.confirm) {
                        this.historyList.splice(index, 1);
                        uni.setStorageSync('searchHistory', JSON.stringify(this.historyList));
                    }
                }
            });
        },
        clearHistory() {
            uni.showModal({
                title: '确认清空',
                content: '确定要清空所有搜索历史吗？',
                confirmColor: '#d43c33',
                success: (res) => {
                    if (res.confirm) {
                        this.historyList = [];
                        uni.removeStorageSync('searchHistory');
                    }
                }
            });
        },
        // 点击事件处理
        handleHotSearchClick(word) {
            this.searchWord = word;
            this.onSearch();
        },
        handleSuggestClick(word) {
            this.searchWord = word;
            this.onSearch();
        },
        handleHistoryClick(word) {
            this.searchWord = word;
            this.onSearch();
        },
        handleSongClick(id) {
            uni.navigateTo({
                url: `/pages/player/player?songId=${id}`
            });
        }
    }
};
</script>

<style>
/* 基础样式 */
page {
    background-color: #f8f8f8;
    font-family: -apple-system, BlinkMacSystemFont, 'Helvetica Neue', sans-serif;
}

/* 搜索框 */
.search-box {
    display: flex;
    align-items: center;
    background: #f5f5f5;
    border-radius: 36rpx;
    padding: 0 30rpx;
    margin: 20rpx;
    height: 80rpx;
    box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.05);
}

.search-input {
    flex: 1;
    font-size: 28rpx;
    color: #333;
    height: 100%;
    background: transparent;
}

.icon-sousuo {
    font-size: 32rpx;
    color: #999;
    margin-left: 10rpx;
}

/* 历史记录 */
.history-container {
    margin: 20rpx;
    background-color: #fff;
    border-radius: 16rpx;
    padding: 20rpx 0;
    box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.05);
}

.history-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 30rpx 10rpx;
    border-bottom: 1rpx solid #eee;
}

.history-title {
    font-size: 28rpx;
    color: #333;
    font-weight: 500;
}

.clear-history {
    font-size: 24rpx;
    color: #999;
    cursor: pointer;
}

.history-list {
    padding: 10rpx 0;
}

.history-item {
    display: flex;
    align-items: center;
    padding: 20rpx 30rpx;
    font-size: 26rpx;
    color: #666;
    transition: all 0.3s ease;
    position: relative;
}

.history-item:hover {
    background-color: #f8f8f8;
}

.history-item.deleting {
    background-color: #ffe6e6;
}

.history-item .iconfont {
    margin-right: 15rpx;
    font-size: 24rpx;
    color: #999;
}

.history-word {
    flex: 1;
    cursor: pointer;
}

.history-item .icon-delete {
    font-size: 24rpx;
    color: #d43c33;
    cursor: pointer;
    opacity: 0.7;
    transition: opacity 0.3s;
}

.history-item .icon-delete:hover {
    opacity: 1;
}

/* 热门搜索 */
.hot-search {
    margin: 20rpx;
    background-color: #fff;
    border-radius: 16rpx;
    padding: 20rpx 30rpx;
    box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.05);
}

.hot-search-title {
    font-size: 28rpx;
    color: #333;
    font-weight: 500;
    margin-bottom: 20rpx;
}

.hot-search-list {
    display: flex;
    flex-wrap: wrap;
}

.hot-search-item {
    background: #f8f8f8;
    border-radius: 40rpx;
    padding: 14rpx 30rpx;
    margin: 0 20rpx 20rpx 0;
    display: flex;
    align-items: center;
    transition: all 0.3s ease;
    cursor: pointer;
}

.hot-search-item:hover {
    transform: translateY(-2rpx);
    box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.08);
}

.hot-search-rank {
    font-size: 24rpx;
    color: #999;
    margin-right: 15rpx;
    width: 24rpx;
    text-align: center;
}

.top-three {
    color: #d43c33;
}

.hot-search-word {
    font-size: 26rpx;
    color: #333;
}

/* 搜索建议 */
.search-suggest {
    margin: 20rpx;
    background-color: #fff;
    border-radius: 16rpx;
    box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.05);
}

.search-suggest-list {
    border-top: none;
}

.search-suggest-item {
    display: flex;
    align-items: center;
    padding: 24rpx 30rpx;
    border-bottom: 1rpx solid #f5f5f5;
    font-size: 26rpx;
    color: #333;
    cursor: pointer;
    transition: background-color 0.2s;
}

.search-suggest-item:hover {
    background-color: #f8f8f8;
}

.search-suggest-item:last-child {
    border-bottom: none;
}

.search-suggest-item .icon-sousuo {
    font-size: 26rpx;
    color: #999;
    margin-right: 20rpx;
}

/* 搜索结果 */
.search-result {
    margin: 20rpx;
}

.result-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20rpx;
}

.result-title {
    font-size: 28rpx;
    color: #333;
    font-weight: 500;
}

.result-count {
    font-size: 24rpx;
    color: #999;
}

.search-result-list {
    background: white;
    border-radius: 16rpx;
    overflow: hidden;
    box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.05);
}

.search-result-item {
    display: flex;
    margin: 0 30rpx;
    padding: 24rpx 0;
    align-items: center;
    border-bottom: 1rpx solid #f5f5f5;
    transition: all 0.3s ease;
    cursor: pointer;
}

.search-result-item:last-child {
    border-bottom: none;
}

.search-result-item:hover {
    background-color: #fafafa;
    transform: translateX(5rpx);
}

.song-info {
    display: flex;
    align-items: center;
    flex: 1;
}

.song-index {
    font-size: 26rpx;
    color: #999;
    width: 40rpx;
    text-align: center;
    margin-right: 10rpx;
}

.song-details {
    flex: 1;
}

.song-name {
    font-size: 28rpx;
    color: #333;
    margin-bottom: 8rpx;
}

.song-artist {
    font-size: 22rpx;
    color: #999;
}

.icon-play {
    font-size: 32rpx;
    color: #d43c33;
}

/* 空结果 */
.empty-result {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 500rpx;
}

.icon-search-empty {
    font-size: 120rpx;
    color: #e0e0e0;
    margin-bottom: 30rpx;
}

.empty-text {
    font-size: 28rpx;
    color: #999;
}
</style>